package com.howard.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 执行时间拦截器
 * @author <a href="mailto:howard.he0329@gmail.com">Howard He</a>
 *
 */
public class TimerInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(TimerInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if(logger.isDebugEnabled()) {
			logger.debug("Interceptor Name: " + this.getClass().getSimpleName());
		}
		long startTime = System.currentTimeMillis();
		request.setAttribute("startTime", startTime);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		long startTime = (Long)request.getAttribute("startTime");
		long endTime = System.currentTimeMillis();
		if(logger.isDebugEnabled()) {
			logger.debug(handler.getClass().getSimpleName() + " Execute Time: " + (endTime - startTime) + "ms");
		}
		modelAndView.addObject("executeTime", (endTime - startTime) + "ms");
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
	}

}
